package com.cowmooed.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicLong;

/**
 * 雪花算法ID生成器
 * 用于生成分布式环境下唯一的ID
 * 结构: 符号位(1位) + 时间戳(41位) + 机器ID(5位) + 数据中心ID(5位) + 序列号(12位)
 */
@Slf4j
@Component
public class SnowflakeIdGeneratorUtil {

    // 起始时间戳 (2023-01-01 00:00:00)
    private static final long START_TIMESTAMP = 1672502400000L;

    // 机器ID位数
    private static final long WORKER_ID_BITS = 5L;
    // 数据中心ID位数
    private static final long DATACENTER_ID_BITS = 5L;
    // 序列号位数
    private static final long SEQUENCE_BITS = 12L;

    // 机器ID最大值
    private static final long MAX_WORKER_ID = ~(-1L << WORKER_ID_BITS);
    // 数据中心ID最大值
    private static final long MAX_DATACENTER_ID = ~(-1L << DATACENTER_ID_BITS);
    // 序列号最大值
    private static final long MAX_SEQUENCE = ~(-1L << SEQUENCE_BITS);

    // 机器ID左移位数
    private static final long WORKER_ID_SHIFT = SEQUENCE_BITS;
    // 数据中心ID左移位数
    private static final long DATACENTER_ID_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS;
    // 时间戳左移位数
    private static final long TIMESTAMP_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS + DATACENTER_ID_BITS;

    // 数据中心ID
    private final long datacenterId;
    // 机器ID
    private final long workerId;
    // 序列号
    private final AtomicLong sequence = new AtomicLong(0L);
    // 上一次生成ID的时间戳
    private long lastTimestamp = -1L;

    /**
     * 构造函数
     * 使用默认的机器ID和数据中心ID
     */
    public SnowflakeIdGeneratorUtil() {
        this(1L, 1L);
    }

    /**
     * 构造函数
     * @param workerId 机器ID
     * @param datacenterId 数据中心ID
     */
    public SnowflakeIdGeneratorUtil(long workerId, long datacenterId) {
        if (workerId > MAX_WORKER_ID || workerId < 0) {
            throw new IllegalArgumentException(String.format("Worker ID can't be greater than %d or less than 0", MAX_WORKER_ID));
        }
        if (datacenterId > MAX_DATACENTER_ID || datacenterId < 0) {
            throw new IllegalArgumentException(String.format("Datacenter ID can't be greater than %d or less than 0", MAX_DATACENTER_ID));
        }
        this.workerId = workerId;
        this.datacenterId = datacenterId;
        log.info("SnowflakeIdGenerator initialized with workerId={}, datacenterId={}", workerId, datacenterId);
    }

    /**
     * 生成下一个ID
     * @return 生成的唯一ID
     */
    public synchronized long nextId() {
        long timestamp = currentTimeMillis();

        // 如果当前时间小于上一次生成ID的时间戳，说明系统时钟回退过，抛出异常
        if (timestamp < lastTimestamp) {
            log.error("Clock moved backwards. Refusing to generate id for {} milliseconds", lastTimestamp - timestamp);
            throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
        }

        // 如果是同一时间生成的，则序号递增
        if (timestamp == lastTimestamp) {
            // 序列号自增
            sequence.set((sequence.get() + 1) & MAX_SEQUENCE);
            // 如果序列号达到最大值，则阻塞到下一个毫秒
            if (sequence.get() == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            // 时间戳改变，序列号重置为0
            sequence.set(0L);
        }

        // 更新上一次生成ID的时间戳
        lastTimestamp = timestamp;

        // 组合ID
        // 时间戳部分 + 数据中心部分 + 机器部分 + 序列号部分
        return ((timestamp - START_TIMESTAMP) << TIMESTAMP_SHIFT)
                | (datacenterId << DATACENTER_ID_SHIFT)
                | (workerId << WORKER_ID_SHIFT)
                | sequence.get();
    }

    /**
     * 阻塞到下一个毫秒，直到获得新的时间戳
     * @param lastTimestamp 上一次生成ID的时间戳
     * @return 当前新的时间戳
     */
    private long tilNextMillis(long lastTimestamp) {
        long timestamp = currentTimeMillis();
        while (timestamp <= lastTimestamp) {
            timestamp = currentTimeMillis();
        }
        return timestamp;
    }

    /**
     * 获取当前时间戳
     * @return 当前时间戳
     */
    protected long currentTimeMillis() {
        return System.currentTimeMillis();
    }
}